#include <nice2d/actions/scaleaction.h>
#include <nice2d/entity.h>

class ScaleActionData
{
public:
    sf::Vector2f targetScale = sf::Vector2f(1.0f, 1.0f);
    float currentTime = 0.0f;
    std::optional<sf::Vector2f> vel;
};

ScaleAction::ScaleAction(const sf::Vector2f &targetScale, float duration):
    FiniteTimeAction(duration),
    data(new ScaleActionData())
{
    data->targetScale = targetScale;
}

ScaleAction::~ScaleAction()
{
}

void ScaleAction::update(float deltaTime)
{
    auto owner = getOwner();
    if (owner.expired())
        return;

    auto target = std::dynamic_pointer_cast<Entity>(owner.lock());

    if (!data->vel.has_value()) {
        auto vel = data->targetScale - target->getScale();
        vel /= getDuration();
        data->vel = vel;
    }

    if (data->vel.has_value()) {
        data->currentTime += deltaTime;
        auto scale = data->vel.value() * deltaTime;
        scale += target->getScale();
        target->setScale(scale);
        if (data->currentTime >= getDuration()) {
            stop();
        }
    }
}
